<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Repository\Contracts\FavoriteInterface;
use App\Support\Helper\CommonHelper;
use Illuminate\Http\Request;
use Auth;

/**
 * @Author:: HuangYin
 * @DateTime: 2017/8/20 16:45
 */
class FavoriteController extends Controller
{
    /**
     * @var Request
     */
    protected $request;

    /**
     * @var FavoriteInterface
     */
    protected $favorite;

    /**
     * @var int
     */
    protected $uid;

    /**
     * FavoriteController constructor.
     * 
     * @param Request $request
     * @param FavoriteInterface $favorite
     */
    public function __construct(Request $request, FavoriteInterface $favorite)
    {
        $this->request = $request;

        $this->favorite = $favorite;

        $this->uid = CommonHelper::getToken(Auth::user())['uid'] ?: 0;
    }

    /**
     * 列表
     *
     * @param $target
     * @return \Illuminate\Http\JsonResponse
     */
    public function index($target)
    {
        $limit = $this->request->input('limit', 15);
        $page = $this->request->input('page', 1);
        $searchMap = $this->searchMap([
            ['uid', $this->uid, '='],
            ['target', $target, '='],
            ['status', 1, '=']
        ]);
        $list = $this->favorite->lists($limit, $page, $searchMap, $target);

        return $this->success($list);
    }

    /**
     * 收藏
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function create()
    {
        $data = $this->request->only(['target', 'target_id']);
        $data['uid'] = $this->uid;
        $list = $this->favorite->created($data);

        return $this->success($list);
    }

    /**
     * 取消
     *
     * @param $target
     * @param $target_id
     * @return \Illuminate\Http\JsonResponse
     */
    public function cancel($target, $target_id)
    {
        $searchMap = $this->searchMap([
            ['uid', $this->uid, '='],
            ['target', $target, '='],
            ['target_id', $target_id, '='],
        ]);
        $list = $this->favorite->updateStatus($searchMap, 2);

        return $this->success($list);
    }
}